package com.andy.retrofitclient;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Andy on 16/7/15.
 */
public class RetrofitManager {

    private static RetrofitManager sRetrofitManager;
    private final Retrofit mRetrofit;

    private OkHttpClient client;

    private RetrofitManager(){

        initOkHttpClient();

        mRetrofit = new Retrofit.Builder().baseUrl("http://api.m.mtime.cn")
                //.client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private void initOkHttpClient() {
//       client = new OkHttpClient.Builder()
//                .addNetworkInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request();
//
//                        long t1 = System.nanoTime();
//                        Log.e("OKHTTP",String.format("Sending request %s on %s%n%s",
//                                request.url(), chain.connection(), request.headers()));
//
//                        Response response = chain.proceed(request);
//
//                        long t2 = System.nanoTime();
//                        Log.e("OKHTTP",String.format("Received response for %s in %.1fms%n%s",
//                                response.request().url(), (t2 - t1) / 1e6d, response.body().string()));
//                        return response;
//                    }
//                }).build();
    }


    public static  RetrofitManager getInstance() {
        if (sRetrofitManager == null) {
            sRetrofitManager = new RetrofitManager();
        }

        return sRetrofitManager;
    }

    public static <T> T Factory(Class<T> cls){
        return getInstance().createAPI(cls);
    }

    public <T> T createAPI(Class<T> cls){
        return mRetrofit.create(cls);
    }
}
